import { appendObjectToUrl } from './utils'

const env = 'local'

const domain = {
  local: 'https://amsplink.usemock.com',
  prod: 'https://api.amsp.link'
}

const Fetch = async (
  params: { url: string; method: 'GET' | 'POST'; file: File; needData?: boolean },
  data: object
) => {
  const { url, method = 'GET', needData = true, file } = params

  let fetchUrl = `${domain[env]}/${url}`
  if (method === 'GET') {
    fetchUrl = appendObjectToUrl(fetchUrl, data)
  }

  const config: { body?: string | FormData } = {}

  if (file) {
    const fd = new FormData()
    fd.append('file', file)
    config.body = fd
  } else if (method === 'POST') {
    config.body = JSON.stringify(data)
  }

  const token = ''

  const oriText = await fetch(fetchUrl, {
    method,
    headers: {
      'Content-Type': 'application/json; charset=UTF-8',
      Authorization: token ? `Bearer ${token}` : ''
    },
    ...config
  })
    .then(res => res.text())
    .catch(error => {
      console.log(`[${fetchUrl}]`, error)
      // Toast.show({ content: '系统错误，请稍后再试~' })
    })

  let res = { code: 500 }
  try {
    res = JSON.parse(oriText)
  } catch {
    //
  }

  if (!needData) return res

  if (needData && res && res.code === 200) {
    return res.data
  }
}

export default Fetch
